package team.hyznrj.studentsys.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import team.hyznrj.studentsys.constant.CookieConstant;
import team.hyznrj.studentsys.dao.mapper.CollegeMajorMapper;
import team.hyznrj.studentsys.entity.account.AccountInfo;
import team.hyznrj.studentsys.utils.CookieUtil;
import team.hyznrj.studentsys.utils.RedisUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能:
 * 将登录后的用户权限进行传递，同时阻截未登录用户
 * @author ReMidDream/ZZF
 * @date 2018年9月10日 
 **/
@Component
public class LoginInterceptor implements HandlerInterceptor {
	@Autowired
    RedisUtil redisUtil;
    @Autowired
	CollegeMajorMapper mapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	response.setHeader("Content-type", "application/json;charset=UTF-8");

        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);

        if (cookie==null || StringUtils.isEmpty(cookie.getValue())) {
           return false;
        }
        String tokenValue = cookie.getValue();

        if (tokenValue == null) {
            return false;
        }

        AccountInfo account = redisUtil.getAccount(cookie.getValue());

        if (account == null) {
            return false;
        }
        String flag = mapper.getFlag(account.getCollegeMajorId())+account.getId();
        request.setAttribute("flag", flag);
        System.out.println(request.getRequestURL()+"  #");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
